#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/12 10:12
# @Author  : 李中华
# @Email   : 1260429766@qq.com
# @File    : cryptoTool.py
# pip install pycryptodomex
import binascii
import base64
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_v1_5
import os
from ProjectPath import projectPath

# public_File = os.path.join(projectPath,'config','publicKey')
# private_File = os.path.join(projectPath,'config','privateKey')


class RsaCrypto():

    def __init__(self):
        try:
            key = RSA.generate(2048)
            encrypted_key = key.exportKey(pkcs=8)
            self.public_key = key.publickey().exportKey().decode('utf-8')
            self.private_key = encrypted_key.decode('utf-8')
            # print({'state': "success", 'message': {'public_key': self.public_key, 'private_key': self.private_key}})
        except Exception as err:
            print({'state': "fail", 'message': str(err)})

    def create_rsa_key(self):
        '''生成RSA秘钥对，现修改，构造函数代替此功能'''
        try:
            key = RSA.generate(2048)
            encrypted_key = key.exportKey(pkcs=8)

            public_key = key.publickey().exportKey().decode('utf-8')
            private_key = encrypted_key.decode('utf-8')

            # with open(public_File,'w') as public:
            #     public.write(public_key)
            # with open(private_File,'w') as private:
            #     private.write(private_key)

            return {'state': "success", 'message': {'public_key': public_key, 'private_key': private_key}}
        except Exception as err:
            return {'state': "fail", 'message': str(err)}

    def encrypt(self, plaintext):
        '''此前从文件中读取公钥，现修改，不从文件中去公钥调用私有RSA加密方法'''
        # with open(public_File, 'r', encoding='utf-8') as public:
        #     public_key = public.readlines()
        #     print(public_key)
        #     public_key = ''.join(public_key)

        return self.__encrypt(self.public_key, plaintext)

    def decrypt(self, hex_data):
        '''此前从文件中读取私钥，现修改，不从文件中调用私有RSA解密方法'''
        # with open(private_File, 'r', encoding='utf-8') as private:
        #     private_key = private.readlines()
        #     private_key = ''.join(private_key)
        return self.__decrypt(self.private_key, hex_data)

    def loginPWDEncrypt(self, plaintext):
        '''web登录密码RSA加密'''

        key = """-----BEGIN PUBLIC KEY-----        
        MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANL378k3RiZHWx5AfJqdH9xRNBmD9wGD2iRe41HdTNF8RUhNnHit5NpMNtGL0NPTSSpPjjI1kJfVorRvaQerUgkCAwEAAQ==
        -----END PUBLIC KEY-----"""  # 注意上述key的格式
        rsakey = RSA.importKey(key)
        cipher = PKCS1_v1_5.new(rsakey)  # 生成对象
        cipher_text = base64.b64encode(cipher.encrypt(plaintext.encode(encoding="utf-8")))  # 对传递进来的用户名或密码字符串加密
        value = cipher_text.decode('utf8')  # 将加密获取到的bytes类型密文解码成str类型
        return value

    def __encrypt(self, public_key, plaintext):
        '''RSA加密方法封装'''
        try:
            recipient_key = RSA.import_key(public_key)
            cipher_rsa = PKCS1_v1_5.new(recipient_key)

            en_data = cipher_rsa.encrypt(plaintext.encode('utf-8'))
            hex_data = binascii.hexlify(en_data).decode('utf-8')

            return {'state': "success", 'message': hex_data}
        except Exception as err:
            return {'state': 0, 'message': str(err)}

    def __decrypt(self, private_key, hex_data):
        '''RSA解密方法封装'''
        try:

            private_key = RSA.import_key(private_key)
            cipher_rsa = PKCS1_v1_5.new(private_key)

            en_data = binascii.unhexlify(hex_data.encode('utf-8'))
            data = cipher_rsa.decrypt(en_data, None).decode('utf-8')

            return {'state': "success", 'message': data}
        except Exception as err:
            return {'state': "fail", 'message': str(err)}

if __name__ == '__main__':
    r1 = RsaCrypto()
    encrypt = r1.encrypt('mskj0417')['message']
    print(encrypt)
    # print(r1.create_rsa_key()['message'])
    # print(RsaCrypto().loginPWDEncrypt('mskj0417'))
    decrypt = r1.decrypt(encrypt)['message']
    print(decrypt)
    # print(r1.loginPWDEncrypt('mskj0417')['message'])


